# -*- coding:utf-8 -*-
"""
@Created on : 2022/4/22 22:02
@Author: binkuolo
@Des: 工具函数
"""

import hashlib
import random
import time
import uuid
from passlib.handlers.pbkdf2 import pbkdf2_sha256
import aiohttp


def random_str():
    """
    唯一随机字符串
    :return: str
    """
    only = hashlib.md5(str(uuid.uuid1()).encode(encoding='UTF-8')).hexdigest()
    return str(only)


if __name__ == '__main__':
    print(random_str())


def en_password(psw: str):
    """
    密码加密
    :param psw: 需要加密的密码
    :return: 加密后的密码
    """
    password = pbkdf2_sha256.hash(psw)
    return password


def check_password(password: str, old: str):
    """
    密码校验
    :param password: 用户输入的密码
    :param old: 数据库密码
    :return: Boolean
    """
    check = pbkdf2_sha256.verify(password, old)
    if check:
        return True
    else:
        return False


def code_number(ln: int):
    """
    随机数字
    :param ln: 长度
    :return: str
    """
    code = ""
    for i in range(ln):
        ch = chr(random.randrange(ord('0'), ord('9') + 1))
        code += ch

    return code


async def process_payment_request(name, money, clientip,pid):
    """
    详细文档https://peak.6knn.cn/User/PrdDoc/Index
    处理支付请求
    :param notify_url: 服务器异步通知地址
    :param return_url: 页面跳转通知地址，此处为二维码
    :param name: 商品名称
    :param money: 金额
    :param clientip: 用户 IP 地址
    :return: 支付请求响应
    """
    # 商户密钥
    key = "DfK1MGklxVEb7dsn17qLM0KmJ6pg8yZC"
    # 使用时间戳作为交易号
    out_trade_no = int(time.time())
    # 商户订单号
    order_no = random_str()
    # 构建请求参数
    params = {
        'pid': 1031,
        'type': 'wxpay',
        'out_trade_no': order_no,
        'notify_url': "https://ylxue.top//api/user/pay",
        'return_url': pid,
        'name': name,
        'money': money,
        'clientip': clientip,
        'param': '',
        'sign_type': 'MD5',
    }

    # 生成签名
    sorted_params = sorted([(k, v) for k, v in params.items() if k not in ['sign', 'sign_type'] and v])
    query_string = '&'.join([f"{k}={v}" for k, v in sorted_params])
    sign = hashlib.md5((query_string + key).encode('utf-8')).hexdigest()
    params['sign'] = sign

    # 发送请求
    url = "https://peak.6knn.cn/mapi.php"
    async with aiohttp.ClientSession() as session:
        async with session.post(url, data=params) as response:
            response_json = await response.json()

    # 处理响应
    if response_json['code'] == 1:
        print("支付请求成功")
        if 'payurl' in response_json:
            # print(f"支付跳转URL: {response_json['payurl']}")
            response_json['order_no'] = order_no
            return response_json
        elif 'qrcode' in response_json:
            response_json['qrcode'] = fr"https://peak.6knn.cn/QrCode/Index?data={response_json['qrcode']}"
            # print(f"二维码链接: https://peak.6knn.cn/QrCode/Index?data={response_json['qrcode']}")
            response_json['order_no']=order_no
            return response_json
    else:
        print(f"支付请求失败: {response_json['msg']}")

    return response_json
